#!/bin/env
"""
Uses gdal2tiles to create raster overlays for the alternate models
Creates the final KML file 'wrapper' 
"""
import os
import glob

write_kml_wrapper = False

mods = [x.replace('.vrt','').replace('out/','') for x in glob.glob('out/alt_*.vrt')]
for mod in mods:
    cmd = 'gdal2tiles.py -k -u "http://maps5.msi.ucsb.edu/media/" -z 2-9 -p geodetic out/%s.vrt ../mediaroot/kml_%s' % (mod,mod) 
    print cmd
    print os.popen(cmd).readlines()

#### Begin KML Wrapper stuff
kml = """<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>California Current Marine Threats Model</name>
<ScreenOverlay>
  <name>Legend</name>
  <color>ffffffff</color>
  <visibility>1</visibility>
  <Icon>
    <href>http://maps5.msi.ucsb.edu/media/ca_legend.png</href>
  </Icon>
      <overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
      <screenXY x="0" y="0" xunits="pixels" yunits="insetPixels"/>
      <size x="212" y="22" xunits="pixel" yunits="pixel"/>
</ScreenOverlay>

<Folder>
	<name>Impact Model Alternatives</name>
	<visibility>1</visibility>
	<open>1</open>
	<Style>
         <ListStyle>
	  <listItemType>radioFolder</listItemType>            
	 </ListStyle>    
        </Style>
%s 

</Folder>
</Document>
</kml>"""

orig = """

	<NetworkLink>
		<name>California Current Model Results - Original</name>
		<visibility>1</visibility>
		<Style>
			<ListStyle>
				<listItemType>radioFolder</listItemType>
				<bgColor>00ffffff</bgColor>
				<maxSnippetLines>2</maxSnippetLines>
			</ListStyle>
		</Style>
		<Link>
			<href>http://maps5.msi.ucsb.edu/media/kml/doc.kml?</href>
			<viewRefreshMode>onStop</viewRefreshMode>
			<viewRefreshTime>1</viewRefreshTime>
		</Link>
	</NetworkLink>
"""

model = """
	<NetworkLink>
		<name>Human Impacts- %s</name>
		<visibility>0</visibility>
		<Link>
			<href>http://maps5.msi.ucsb.edu/media/kml_%s/doc.kml?</href>
			<viewRefreshMode>onStop</viewRefreshMode>
			<viewRefreshTime>1</viewRefreshTime>
		</Link>
	</NetworkLink>
"""

models_kml = []
for mod in mods:
    models_kml.append( model % (mod,mod))

final_kml = kml % ''.join(models_kml) 

if write_kml_wrapper:
    fh = open("/usr/local/src/marinethreats/mediaroot/layers/uploaded-kml/California_Current_Marine_Threats_1.kml",'w')
    fh.write( final_kml )
    fh.close()
